{include file="admin@public/header" /}

<link rel="stylesheet" href="/public/static/admin/easyui/layui-v2.6.8/css/layui.css">
<link href="/public/static/admin/blue/bills.css" rel="stylesheet" type="text/css">

<style>
    /*#barCodeInsert{margin-left: 10px;font-weight: 100;font-size: 12px;color: #fff;background-color: #B1B1B1;padding: 0 5px;border-radius: 2px;line-height: 19px;height: 20px;display: inline-block;}*/
    /*#barCodeInsert.active{background-color: #23B317;}*/
    .url-box {
        padding: 5px 10px;
        line-height: 20px;
        cursor: pointer;
    }

    .url-box a {
        margin-right: 5px;
    }

    .con-header dd #editBills {
        background: url(/public/static/admin/css/img/edit.png);
        display: inline-block;
        width: 13px;
        height: 12px;
    }

    #check_history {
        background: green;
        border-radius: 10px 10px;
        width: 80px;
        text-align: center;
    }

    #check_history a {
        color: #fff;
    }

    .wrapper_con {
        overflow-y: auto;
        overflow-x: hidden;
    }

    .ui-jqgrid a.srcOrderNo {
        text-decoration: none;
        cursor: pointer;
    }

    .ui-jqgrid a.srcOrderNo:hover {
        text-decoration: none;
    }

    .layui-form-radio {
        margin-top: 0;
    }

    .layui-form-radio>i:hover,
    .layui-form-radioed>i {
        color: #3CBAFF;
    }

    .pcnone {
        display: none !important;
    }

    .target_box {
        position: relative;
    }

    .target_box:after,
    .target_box:before {
        border: solid transparent;
        content: ' ';
        height: 0;
        bottom: 100%;
        position: absolute;
        width: 0;
    }

    .target_box:after {
        border-width: 8px;
        border-bottom-color: #fff;
        left: 27px;
    }

    .target_box:before {
        border-width: 10px;
        border-bottom-color: #aaa;
        left: 25px;
    }

    .shadow.opera-log-box::before,
    .shadow.opera-log-box::after {
        border: solid transparent;
        content: ' ';
        height: 0;
        bottom: 100%;
        position: absolute;
        width: 0;
    }

    .shadow.opera-log-box:after {
        border-width: 8px;
        border-bottom-color: #FFEED4;
        right: 60px;
    }

    .shadow.opera-log-box:before {
        border-width: 10px;
        border-bottom-color: #E1B77E;
        right: 58px;
    }
</style>

<div class="wrapper">
    <div class="mod-toolbar-top mr0 cf dn" id="toolTop"></div>
    <div class="bills cf">
        <div class="con-header layui-form">
            <dl class="cf">
                <dd class="mr20">
                    <label>供应商:</label>
                    <span class="ui-combo-wrap" id="customer" style="width: 198px;">
                        <i class="ui-icon-ellipsis" onclick="chooseSupplier()"></i>
                        <input type="text" name="" class="input-txt" autocomplete="off" value="(空)" data-ref="date"
                            style="width: 188px;"></span>
                </dd>
                <dd class="mr20">
                    <label>单据日期:</label>
                    <input type="date" id="dj_time" class="ui-input " value="{$today}" style="width: 125px;">
                </dd>
                <dd class="mr20 tr" id="transTypeBox">
                    <label>业务类别:</label>
                    <span class="ui-combo-wrap ui-combo-active" id="transType" style="width: 88px;">
                        <input type="text" name="" class="input-txt" autocomplete="off" value="盘盈" data-ref="date"
                            readonly="readonly" style="cursor: default; width: 62px;" id="transTypeVal">
                        <i class="trigger"></i>
                    </span>
                    <div class="ui-droplist-wrap" id="transTypePopupBox"
                        style="position: absolute; top: 69.8906px; z-index: 1000; width: 88px; display: none; left: 570px;text-align: left;">
                        <div class="droplist"
                            style="position: relative; overflow: auto; min-height: 150px; height: 150px;">
                            <div class="list-item selected" data-value="1" title="盘盈">盘盈</div>
                            <div class="list-item" data-value="0" title="其他入库">其他入库</div>
                        </div>
                    </div>
                </dd>


                <dd id="identifier" style="float:right">
                    <label>单据编号:</label>
                    <span id="number">{$sn}</span>
                    <i id="editBills"></i>

                    <span class="ui-combo-wrap ui-combo-active ctn-wrap" id="storage1"
                        style="display: none;position: relative;overflow: visible;">
                        <input type="text" class="input-txt" autocomplete="off" id="storageInput1"
                            value="GHDD20210809001"><i class="trigger"></i>
                        <div class="ui-droplist-wrap" id="storageList1"
                            style="position: absolute; top: 30px; z-index: 1000; width: 100%; display: none; left: 0;">
                            <div class="droplist"
                                style="position: relative; overflow: auto; min-height: 150px; height: 150px;">
                                <div class="list-item" onclick="chooseSelect('1','0','GHDD202108090012')">
                                    {$sn}</div>
                            </div>
                        </div>
                    </span>

                </dd>

            </dl>
            <hr class="hrcls">
        </div>

        <div class="wrapper_con">

            <span id="config" class="ui-config"><a href="#" class="ui-icon-config-new"></a></span>
            <div class="grid-wrap">
                <table id="grid"></table>
                <div id="page"></div>
            </div>
            <div class="cf" id="bottomField">
                <span id="groupBtn">

                    <a id="savaAndAdd" class="ui-btn ui-btn-sp">保存并新增</a>
                    <a id="save" class="ui-btn">保存</a>
                    <a id="shenhe" class="ui-btn">审核</a>
                </span>
            </div>
            <div id="mark"></div>
        </div>

        <div class="con-footer cf">
            <div class="mb10">
                <textarea type="text" id="note" class="ui-input ui-input-ph" placeholder="暂无备注信息"></textarea>
            </div>

            <ul id="user-field">
                <li class="udfLink"><a class="user-field">自定义字段</a></li>
            </ul>

            <div class="cf fr">
                <a class="ui-btn-bill ui-btn-hl menu-btn mrb ui-btn-add ta" tabid="purchaseinvPo" data-right="PU_ADD"
                    tabTxt="购货单记录" parentOpen="true" rel="pageTab" _href="/store/pandian/index.html"><span></span>历史单据</a>
                <a href="#" id="operaLog" class="ui-btn">操作日志</a>
            </div>
        </div>
    </div>
</div>



<!--  以隐藏的方式获取商品的样式 ，作用是样式 -->
<div id="pelem_goods" style="display:none;"> </div>
<div id="p_store_id" style="display: none"></div>
<!--  以隐藏的方式获取商品的样式 ，作用是赋值 -->
<div style="display:none;">
    <input type="text" id="supplierid" value="0" autocomplete="off" readonly="">
    <input type="text" id="goodsname" value="" autocomplete="off" readonly="">
    <input type="text" id="type" value="1" autocomplete="off" readonly="">
    <input type="text" id="store_name" value="" autocomplete="off" readonly="">
    <input type="text" id="total_price" value="0" autocomplete="off" readonly="">
</div>

<!-- 仓库弹窗 -->
<div class="ui-droplist-wrap" id="ck_wrap" style="position: absolute; z-index: 1000; width: 102px;display:none;">
    <div class="droplist" id="ck_list" style="position: relative; overflow: auto; min-height: 150px; height: 150px;">
        {volist name="store" id="vo"}
        <div class="list-item" store_id="{$vo.id}" title="{$vo.name}">{$vo.name}</div>
        {/volist}
    </div>
</div>



<script type="text/javascript">
    var edit_row = 0;
    var edit_col = 0;
    var row_id = 0;
    var col_name = 0;
    $(document).ready(function () {
        var goods = '<span class="red">*</span>商品<label> -- 扫描枪录入</label><span id="barCodeInsert" class="close" onclick="smq();"><span class="ui-icon-circle"></span></span>';
        var col4 = '<span id="outstore" onclick="outstore();"><span class="red">*</span>仓库<small id="batchStorageA">批量</small></span>';
        var inventory = '可用库存<img src="/public/static/admin/css/img/help.png" style="width: 20px;display: inline-block;margin-left: 5px;" onclick="snapshotTipsFun()" id="snapshotTipsBtn"/>';
        $("#grid").jqGrid({
            url: '/store/invoi/edit.html?ajax=100&pid={$pid}',
            datatype: "json",//数据来源，本地数据（local，json,jsonp,xml等）
            height: '90%',//高度，表格高度。可为数值、百分比或'auto'
            colNames: ['', goods, '单位', col4, inventory, '<span class="red">*</span>数量', '入库单价', '入库金额', '备注', '商品ID', '仓库id', '单位id'],
            colModel: [
                { name: '', width: 70, formatter: cLink },
                {
                    name: "goodsname",
                    label: "商品",
                    width: 300,
                    title: !0,
                    classes: "goods",
                    editable: true,
                    edittype: "custom",
                    editoptions: {
                        custom_element: function (t, e) {
                            $("#pelem_goods").html('<div class="pr" id="elem_goods"><input type="text" value="'+t+'" class="textbox  customelement" name="goodsname" autocomplete="off" ><span class="ui-icon-ellipsis"></span></div>');
                            return $("#elem_goods");
                        },
                        custom_value: function (t, e, a) {
                            var ad = $("#goodsname").val();
                            $("#goodsname").val("");//重置赋值
                            return ad;
                        },
                        trigger: "ui-icon-ellipsis"
                    }
                },

                { name: 'dw', width: 100, label: "单位" },
                {
                    name: "store_name",
                    width: 100,
                    link: "inventory",
                    editable: true,
                    edittype: "custom",
                    editoptions: {
                        custom_element: function (t, e) {
                            $("#p_store_id").html('<div class="pr" id="store_id"><input type="text" value="'+t+'" class="textbox storageAuto customelement ui-combo-active" name="locationName" autocomplete="off" id="1_locationName" style="outline: -webkit-focus-ring-color auto 5px;"><span class="ui-icon-triangle-1-s" id="st_id"></span></div>');
                            return $("#store_id");
                        },
                        custom_value: function (t, e, a) {
                            var ba = $("#store_name").val();
                            $("#store_name").val("");
                            return ba;
                        },

                        trigger: "ui-icon-triangle-1-s"
                    }
                },
                { name: 'use_ck', width: 80, label: "可用库存", },
                {
                    name: 'number', width: 80, label: "数量", editable: true, editoptions: {
                        size: 25, dataEvents: [
                            {
                                type: 'change',     //blur,focus,change............. 
                                fn: function (e) {
                                    reload_val();
                                }
                            }]
                    }
                },
                {
                    name: 'price', width: 100, editable: true, editoptions: {
                        size: 25, dataEvents: [
                            {
                                type: 'change',     //blur,focus,change............. 
                                fn: function (e) {
                                    reload_val();
                                }
                            }]
                    }
                },
                {
                    name: 'jine', width: 100, editable: true, editoptions: {
                        size: 25, dataEvents: [
                            {
                                type: 'change',     //blur,focus,change............. 
                                fn: function (e) {
                                    reload_val();
                                }
                            }]
                    }
                },
                { name: 'mark', width: 150, editable: true },
                { name: 'good_id', hidden: true },
                { name: 'store_id', hidden: true },
                { name: 'unit_id', hidden: true },
            ],
            cellEdit: true,
            cellurl: '/',
            rowNum: 10,
            rowList: [10, 20, 30],
            sortname: 'id',
            sortorder: "desc",
            pagerpos: "left",//分页位置

            pgbuttons: true,//翻页按钮
            pagination: true,
            altRows: !0,
            gridview: !0,
            shrinkToFit: !1,
            cellLayout: 8,
            autowidth: !0,
            pager: "#page",
            viewrecords: !0,
            cmTemplate: {
                sortable: !1,
                title: !1
            },
            // 合计
            footerrow: true,
            loadError: function (t, e, i) {
                parent.Public.tips({
                    type: 1,
                    content: "操作失败了哦，请检查您的网络链接！"
                })
            },
            beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
                col_name = cellname;
                edit_row = iRow;
                edit_col = iCol;
                row_id = rowid;
                var gname = $("#grid").jqGrid("getCell", row_id, 'goodsname');
                $("#goodsname").val(gname);
                var cname = $("#grid").jqGrid("getCell", row_id, 'store_name');
                $("#store_name").val(cname);
            },
        });

        var mydata = [];
        for (var i = 0; i < 5; i++) {
            var obj = { id: i + 1, goodsname: "", dw: "", good_id: "0", mark: "" }
            mydata.push(obj);
        }
        for (var i = 0; i <= mydata.length; i++) {
            jQuery("#grid").jqGrid('addRowData', i + 1, mydata[i]);
        }


    });

</script>
<script type="text/javascript">
    $(document).ready(function () {
        // 选择仓库弹窗
        $(".grid-wrap").on("click", ".ui-icon-triangle-1-s", function (e) {
            var top = $(this).offset().top;
            var left = $(this).offset().left;
            $("#ck_wrap").slideToggle();
            $("#ck_wrap").css({ "top": (top + 22) + "px", "left": (left - 78) + "px" });
        })
        //选择仓库赋值
        $("#ck_wrap #ck_list").on("click", ".list-item", function (e) {
            var title = $(this).attr("title");
            //仓库1
            if (col_name == "store_name") {
                var store_id = $(this).attr("store_id");
                $("#store_name").val(title);
                $("#grid").jqGrid("setCell", row_id, 'store_id', store_id);
                $("#grid").jqGrid("setCell", row_id, 'use_ck', 1000);//库存
                $("#grid").jqGrid("setCell", row_id, 'store_name', title);//及时保存
            }
            $("#grid").saveRow(row_id, false);
            $("#grid").jqGrid("saveCell", edit_row, edit_col);  //保存表格
            $("#ck_wrap").hide();
        });
    })
    //仓库选择框外点击则隐藏
    $(document).mouseup(function (e) {
        if (e.target.id != "st_id") {
            var con = $("#ck_wrap");   // 设置目标区域
            if (!con.is(e.target) && con.has(e.target).length === 0) {
                $("#ck_wrap").hide();
            }
        }
    });

</script>


<script type="text/javascript">
    function reload_val() {
        var rid = row_id;
        var c_name = col_name;
        var $number = parseInt($("#grid").jqGrid("getCell", rid, 'number'));//数量
        var $price = parseFloat($("#grid").jqGrid("getCell", rid, 'price'));//单价
        if (c_name == "number") {
            //改变数量
            $("#grid").jqGrid("setCell", rid, 'jine', $price * $number);//金额--数量乘以单价
        } else if (c_name == "price") {
            //改变单价
            $("#grid").jqGrid("setCell", rid, 'jine', $price * $number);//金额--数量乘以单价
        } else if (c_name == "jine") {
            //改变金额
            var $jine = parseFloat($("#grid").jqGrid("getCell", rid, 'jine'));//金额
            $price = $jine / $number;//销售单价
            $("#grid").jqGrid("setCell", rid, 'price', $price);//单价
        }
        // 合计的变量
        var numbers = $("#grid").getCol('number', false, 'sum');
        var jines = $("#grid").getCol('jine', false, 'sum');
        $("#total_price").val(jines);
        $("#grid").footerData('set', { "goodsname": '合计', number: numbers, jine: jines, });
    }

</script>
<script type="text/javascript">
    $(document).ready(function () {
        // 顶部筛选下拉-业务类别
        $("#transType .trigger").on("click", function () {
            var top = $(this).parent().offset().top;
            var left = $(this).parent().offset().left;
            $(this).parent().next(".ui-droplist-wrap").slideToggle();
            $(this).parent().next(".ui-droplist-wrap").css({ "top": (top + 9) + "px", "left": (left - 21) + "px" });

        });
        // 点击选择业务类别-业务类别
        $("#transTypeBox .ui-droplist-wrap .list-item,.ui-icon-triangle-1-s").on("click", function () {
            $("#transTypeVal").val($(this).attr("title"));
            $("#type").val($(this).attr("data-value"));
            $(this).addClass("selected").siblings().removeClass("selected");
        });
        // 点击下拉框其他位置隐藏-业务类别
        $(document).click(function () {
            $("#transTypePopupBox").hide();
        });
        // 阻止冒泡-业务类别
        $(".trigger,.ctn-wrap,#editBills").click(function (event) {
            event.stopPropagation();
        });
    });

</script>
<script type="text/javascript">
    //选择商品1-1
    $(document).ready(function () {
        //获取商品
        $(".grid-wrap").on("click", ".ui-icon-ellipsis", function (e) {
            pre_choose_goods('/admin/basic/choose_goods.html', this);

        });
    });
    //选择商品1-2
    function pre_choose_goods(url, obj) {
        choose_goods(url, obj, function (res) {
            if (res.btn == 3 && res.status == 1) {
                //console.log(res);
                var data = res.data;
                if (data.status == 1) {

                    var $count = data.info.count;
                    var good_list = data.info.list;
                    var allIds = $("grid").jqGrid('getDataIDs');
                    var ids = $("#grid").getDataIDs();

                    // console.log("当前行");
                    // console.log(row_id);
                    // console.log("长度："+ids.length);
                    // console.log(ids);
                    row_id = parseInt(row_id);
                    var $cha_id = ids.length - row_id;//最后id-当前id
                    var cha_han = $count - $cha_id - 1;//需要补充的行
                    //console.log("cha:"+cha_han);
                    //补充行
                    if (cha_han > 0) {
                        var mydata1 = [];
                        for (var iii = ids.length; iii < ids.length + cha_han; iii++) {
                            var obj = { id: iii + 1, goodsname: "", goodstype: "", goodsmark: "", dw: "", shuliang: "", ck1: "", ck2: "", ck3: "", mark: "", goodsid: "0", ck1_id: "0", ck2_id: "0" }
                            mydata1.push(obj);
                        }
                        console.log(mydata1);
                        for (var iii = 0; iii <= mydata1.length; iii++) {
                            jQuery("#grid").jqGrid('addRowData', ids.length + iii + 1, mydata1[iii]);
                        }

                    }

                    for (let i = 0; i < $count; i++) {
                        //alert(row_id);
                        $("#grid").jqGrid("saveCell", edit_row, edit_col);
                        $("#grid").jqGrid("setCell", row_id + i, 'goodsname', good_list[i].name);
                        $("#grid").jqGrid("setCell", row_id + i, 'dw', good_list[i].dw);
                        $("#grid").jqGrid("setCell", row_id + i, 'unit_id', good_list[i].unit);
                        $("#grid").jqGrid("setCell", row_id + i, 'good_id', good_list[i].id);
                        $("#grid").jqGrid("setCell", row_id + i, 'number', "1");
                        $("#grid").jqGrid("setCell", row_id + i, 'price', good_list[i].price.estimated_purchase_price);//入库单价
                        $("#grid").jqGrid("setCell", row_id + i, 'jine', good_list[i].price.estimated_purchase_price);//金额
                    }

                    // $("#goodsname").val(data.info.name);
                    // //alert(row_id);
                    // $("#grid").jqGrid("saveCell", edit_row, edit_col);
                    // $("#grid").jqGrid("setCell", row_id, 'dw', data.info.dw);
                    // $("#grid").jqGrid("setCell", row_id, 'unit_id', data.info.unit);
                    // $("#grid").jqGrid("setCell", row_id, 'good_id', data.info.id);
                    // $("#grid").jqGrid("setCell", row_id, 'number', "1");
                    // $("#grid").jqGrid("setCell", row_id, 'price', data.info.price.estimated_purchase_price);//入库单价
                    // $("#grid").jqGrid("setCell", row_id, 'jine', data.info.price.estimated_purchase_price);//金额

                    // 合计的变量
                    var numbers = $("#grid").getCol('number', false, 'sum');
                    var jines = $("#grid").getCol('jine', false, 'sum');
                    $("#total_price").val(jines);
                    $("#grid").footerData('set', { "goodsname": '合计', number: numbers, jine: jines });
                } else {
                    layer.msg("获取商品信息失败");
                }
            }
        });
    }
    //选择客户(供应商)
    function chooseSupplier() {
        layer.open({
            type: 2,
            title: "选择供应商",
            shadeClose: true,
            shade: 0.3,
            maxmin: false, //开启最大化最小化按钮
            area: ['775px', '510px'],
            fixed: false, //不固定
            btn: ['确定', '取消'],
            content: "/admin/basic/choose_customer.html",
            btn1: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                var supplierid = body.find('input[name="goodid"]:checked').val();

                if (supplierid == '' || supplierid == null) {
                    layer.msg("请选择供应商");
                    return false;
                } else {
                    //获取商品信息
                    $.get("/admin/basic/one_customer.html", { id: supplierid }, function (data, state) {
                        if (data.status == 1) {
                            $("#customer input").val(data.info.sn + " " + data.info.name);
                            $('#supplierid').val(data.info.id);
                            layer.close(index);
                        } else {
                            layer.msg("获取商品信息失败");
                        }
                    })
                }
                layer.close(index);
                return false;
            },
            btn4: function (index, layero) {
                layer.close(index);
                return false;
            }
        })
    }

</script>
<script type="text/javascript">
    // 增加、删除按钮
    function cLink(cellvalue, options, rowObject) {
        return '<div class="operating"><span class="ui-icon ui-icon-plus" title="新增行" onclick="add()" style="margin-left:8px;"></span> <span class="ui-icon ui-icon-trash" onclick="del(' + rowObject.id + ')" style="margin-left:8px;">删除</span></div>';
    }
    // 表头扫描枪录入的开关
    function smq() {

        if ($("#barCodeInsert").hasClass("close")) {
            $("#barCodeInsert").addClass('open');
            $("#barCodeInsert").removeClass('close');//removeClass

        } else {
            if ($("#barCodeInsert").hasClass("open")) {
                $("#barCodeInsert").addClass('close');
                $("#barCodeInsert").removeClass('open');//removeClass
            }
        }

    }
</script>


<script type="text/javascript">
    var grid=$('#grid');
    // 保存按钮
    $(".wrapper").on("click", "#save", function (e) {
      save_jqgrid(edit_row,edit_col,grid,function(res){
          $("#grid").jqGrid().trigger("reloadGrid");
          layer.msg("保存成功");
      });
    })

    $(".wrapper").on("click", "#savaAndAdd", function (e) {
        //先保存
        if (edit_row != 0 && edit_col != 0) {
            $("#grid").jqGrid("saveCell", edit_row, edit_col);
            edit_row = 0;
            edit_col = 0;
        }
        savedata();

    })

    function savedata() {
        //拿到grid对象
        var obj = $("#grid");
        //获取grid表中所有的rowid值
        var rowIds = obj.getDataIDs();
        //初始化一个数组arrayData容器，用来存放rowData
        var gooddata = new Array();

        if (rowIds.length > 0) {
            for (var i = 0; i < rowIds.length; i++) {
                if (Object.values(obj.getRowData(rowIds[i]))[1] != '') {
                    gooddata.push(obj.getRowData(rowIds[i]));
                }
            }
        }

        var flag = 0;
        var hasuser = 0;
        var hasuser1 = 0;
        var indexArr = [];
        // console.log(gooddata);
        gooddata.forEach(function (self, index) {
            // console.log(self);
            if (self.good_id != null || self.good_id != "") {
                hasuser = hasuser + 1;
                // console.log("self:",self);
                if (self.store_id == null || self.store_id == "") {
                    flag = 1;
                    indexArr.push(index);
                    // console.log("indexArr:",indexArr);
                    return false;
                } else {
                    hasuser1 = hasuser1 + 1;
                }
            }
        });
        if (hasuser == 0) {
            layer.msg("请选择商品");
            // 必填项（商品）
            $("#grid").editCell(1, 2, true);
            return false;
        }

        if (flag == 1) {
            layer.msg("请选择仓库");
            // 必填项（仓库）
            $("#grid").editCell(indexArr[0] + 1, 4, true);
            return false;
        }

        var customerid = $("#supplierid").val();//客户ID
        if (customerid == "") {
            layer.msg("请选择供应商");
            return false;
        }
        //return false;
        var dj_time = $("#dj_time").val();//单据日期
        var sn = $("#number").html();//单据号
        var mark = $("#note").val();//备注
        var total_price = $("#total_price").val();//备注
        var type = $("#type").val();//业务类型

        $.ajax({
            type: 'POST',
            url: "save.html",
            data: { type: type, user_id: customerid, sn: sn, mark: mark, gooddata: gooddata, dj_time: dj_time, total_price: total_price, pandian: '{$pid}', pandiantype: '盘盈单' },
            dataType: "json",
            async: false,
            error: function (request) {
                layer.msg("发送请求失败！");
            },
            success: function (data) {
                if (data.status == 1) {
                    layer.msg(data.msg);
                } else {
                    layer.msg(data.msg);
                }

            }
        });

    }


</script>

{include file="admin@public/footer" /}